package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"social-eco-sys/cache"
	"social-eco-sys/model"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	img := c.PostForm("img")
	word := c.PostForm("word")
	author := c.PostForm("author")
	if img == "" || word == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	data := model.RedBook{
		Img:    img,
		Word:   word,
		Author: author,
	}
	err := model.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败",
		})
		return
	}
	var redbook model.RedBook
	redis_key := "red_book_add" + strconv.Itoa(int(data.ID))
	model.DB.Where("id=?", data.ID).Debug().Find(&redbook)
	JsonData, _ := json.Marshal(redbook)
	cache.Rdb.Set(cache.Ctx, redis_key, JsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var redbook model.RedBook
	err := model.DB.Where("id=?", id).First(&redbook).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": redbook,
	})
}

func Del(c *gin.Context) {
	id := c.Query("id")
	var redbook model.RedBook
	err := model.DB.Where("id=?", id).Delete(&redbook).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "red_book_del"
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func List(c *gin.Context) {
	var list []model.RedBook
	redis_key := "red_book_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&list).Debug()
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": list,
	})
	return
}
